import axios from 'axios'

const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器，将token放入请求头
api.interceptors.request.use(
  config => {
    const authToken = sessionStorage.getItem('authToken') || 'null'
    if (authToken) {
      config.headers['Authorization'] = `Bearer ${authToken}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 网络错误或服务器错误
    if (error.response) {
      // 服务器返回了错误响应
      const errorData = error.response.data
      if (error.response.status === 401) {
        sessionStorage.removeItem('currentUser')
        sessionStorage.removeItem('authToken')
        window.location.href = '/login'
      }
      // 返回错误信息
      return Promise.reject(errorData || error)
    } else if (error.request) {
      // 请求已发出但没有收到响应
      return Promise.reject(new Error('网络错误，请检查后端服务是否启动'))
    } else {
      // 请求配置出错
      return Promise.reject(error)
    }
  }
)

export default api

// API 方法
export const authAPI = {
  login: (username, password) => api.post('/auth/login', { username, password }),
  register: (userData) => api.post('/auth/register', userData)
}

export const addressAPI = {
  getAll: () => api.get('/addresses'),
  create: (addressData) => api.post('/addresses', addressData),
  delete: (ids) => api.delete('/addresses', { data: { ids } })
}

